package com.ghpt.service.impl;

import com.ghpt.service.DataSourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
@Service
public class DataSourceServiceImpl implements DataSourceService {
    @Autowired
    private DataSource dataSource;

    @Override
    public List<String> listAllDatabases() {
        try (Connection conn = dataSource.getConnection()) {
            List<String> databases = new ArrayList<>();
            ResultSet rs = conn.createStatement().executeQuery("SHOW DATABASES");
            while (rs.next()) {
                String db = rs.getString(1);
                if (!db.equalsIgnoreCase("information_schema") &&
                        !db.equalsIgnoreCase("performance_schema") &&
                        !db.equalsIgnoreCase("mysql") &&
                        !db.equalsIgnoreCase("sys")) {
                    databases.add(db);
                }
            }
            return databases;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void createNewDatabase(String newDbName, String baseDbName) throws SQLException {
        try (Connection conn = dataSource.getConnection()) {
            Statement stmt = conn.createStatement();
            stmt.execute("CREATE DATABASE " + newDbName);

            // 获取所有表结构
            ResultSet tables = stmt.executeQuery("SHOW TABLES FROM " + baseDbName);
            while (tables.next()) {
                String table = tables.getString(1);

                // 创建一个新的 Statement 实例以避免 ResultSet 冲突
                try (Statement stmtCreate = conn.createStatement()) {
                    ResultSet rsCreate = stmtCreate.executeQuery("SHOW CREATE TABLE " + baseDbName + "." + table);
                    if (rsCreate.next()) {
                        String createSQL = rsCreate.getString(2);
                        stmtCreate.execute("USE " + newDbName);
                        stmtCreate.execute(createSQL);
                        stmtCreate.execute("INSERT INTO " + newDbName + "." + table + " SELECT * FROM " + baseDbName + "." + table);
                    }
                }
            }
        }
    }


}